package com.gitee.mall.sentinel.controller;

import com.alibaba.csp.sentinel.annotation.SentinelResource;
import com.gitee.common.utils.R;
import com.gitee.mall.sentinel.sentinel.CommonBlockHandler;
import com.gitee.mall.sentinel.sentinel.ExceptionUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.concurrent.atomic.AtomicInteger;

@Slf4j
@RestController
@RequestMapping(value = "/user")
public class UserController {

    AtomicInteger atomicInteger = new AtomicInteger();

    @RequestMapping(value = "/findOrderByUserId/{id}")
    @SentinelResource(value = "findOrderByUserId",
            blockHandlerClass = CommonBlockHandler.class,blockHandler = "blockHandler",
            fallback = "fallback",fallbackClass = ExceptionUtil.class)
    public R findOrderByUserId(@PathVariable("id") Integer id) {


        //int a = 1 / 0;

        // findOrderByUserId  限流规则  2    sentinel dashboard 定义规则

        //feign调用
        //R result = orderFeignService.findOrderByUserId(id);

        log.info("进入请求");
         /*  try {
            // 模拟测试并发线程数限流(设置线程数为1，postman每900ms清求一次，如果在请求一次就会有2个线程并发，而被限流)
            Thread.sleep(1000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }*/

         //降级：模拟慢调用 RT:500ms 比例:0.6 最小请求数：5
        /*int data = atomicInteger.incrementAndGet();
        if (data > 20 && data < 50) {
            try {
                Thread.sleep(600);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }*/

        return new R();
    }

    /**
     * 信息
     */
    @RequestMapping("/info/{id}")
    @SentinelResource(value = "userinfo",
            blockHandlerClass = CommonBlockHandler.class,
            blockHandler = "blockHandler",
            fallbackClass = ExceptionUtil.class,
            fallback = "fallback"
    )
    public R info(@PathVariable("id") Integer id){
        //UserEntity user = userService.getById(id);


        if(id==4){
            throw new IllegalArgumentException("异常参数");
        }

        return R.ok().put("user", "nice");
    }

}
